import { createStore, Store, useStore as baseUseStore } from 'vuex'
import { InjectionKey } from 'vue'
import { homeApi } from '@/api'
import { SETLANGUAGE } from './vuex/types'

// 为 store state 声明类型
export interface AllStateTypes {
	language:string,
	user:{
		username:string
	},
	ads:any,
	info:{
		title:string;
		keywords:string;
		description:string;
	}
}

// 定义 injection key
export const key: InjectionKey<Store<AllStateTypes>> = Symbol('storeKey')

export function useStore() {
	return baseUseStore(key)
}

export function createSSRStore() {
	return createStore<AllStateTypes>({
		state: {
			language:'zh',
			info:{
				title:'',
				keywords:'',
				description:'',
			},
            user:{
				username:'steven'
			},
			ads:[],
		},
		mutations: {
			setAds(state, data) {
				state.ads = data
				return state.ads
			},
			[SETLANGUAGE](state,lang){
				state.language = lang;
			}
		},
		actions: {
			setLanguage({commit},lang){
				commit(SETLANGUAGE,lang);
			},
			updateUser({commit}){
				this.state.user.username = 'uss'
			},
			async getAds({commit}){
				return new Promise(rosolve=>{
					homeApi.getAdsData().then(res=>{
						commit('setAds',res.data.rows)
						rosolve(true)
					})
				})
			}
		}
	})
}
